<script setup lang="ts">
import {Expand, Setting, Switch, SwitchButton, Upload, VideoPlay} from '@element-plus/icons-vue'
import {useRoute, useRouter} from "vue-router";
import {useUserStore} from "../stores/userStore.ts";
import {onMounted, ref, onUnmounted} from "vue";
import {eventBus} from '../utils/eventBus'
import {SetControllerService} from "../../generated";
import {ElMessage} from "element-plus";

interface LoginUser {
  username: string;
  avatar: string;
}

interface ToolbarInfo {
  title: string;
  questionIds: string[]
}

const username = ref('')
const avatar = ref('')
const lastDisabled = ref(true)

const toolbarInfo = ref<ToolbarInfo>({
  title: "题库",
  questionIds: []
})

let router = useRouter();
const route = useRoute();

const toHome = () => {
  router.push("/problem")
}

let userStore = useUserStore();

const fetchToolbarInfo = async () => {
  const mode = route.query.mode;
  const envId = route.query.envId;

  if (!mode || !envId) {
    return;
  }

  try {
    const res = await SetControllerService.getSetDetailUsingGet(envId as string);
    if (res.code !== 0 || !res.data) {
      ElMessage.error('获取题目集信息失败');
      return;
    }

    toolbarInfo.value = {
      title: res.data.title || "题库",
      questionIds: res.data.groups?.flatMap(group =>
          group.questions?.filter(q => q.id).map(q => q.id as string) || []
      ) || []
    };
  } catch (error) {
    ElMessage.error('获取题目集信息失败');
  }
}

onMounted(async () => {
  const loginUser = userStore.loginUser as LoginUser
  username.value = loginUser.username
  avatar.value = loginUser.avatar
  await fetchToolbarInfo();

  eventBus.on('updateLastDisabled', (disabled) => {
    lastDisabled.value = Boolean(disabled)
  });
})

onUnmounted(() => {
  eventBus.off('updateLastDisabled');
})

const toLogin = () => {
  router.push("/user/login")
}

const logout = () => {
  userStore.logout()
  router.push("/")
}

const handleSubmit = () => {
  eventBus.emit('submitCode')
}

const handleOpenTab = () => {
  eventBus.emit('showTab')
}

const handleNavigation = (direction: 'next' | 'prev') => {
  const mode = route.query.mode;
  const envId = route.query.envId;
  const currentId = route.params.id;

  if (mode && envId) {
    // 学习计划模式
    const currentIndex = toolbarInfo.value.questionIds.findIndex(item => item === currentId);
    const targetIndex = direction === 'next' ? currentIndex + 1 : currentIndex - 1;

    if (direction === 'next' && targetIndex > toolbarInfo.value.questionIds.length - 1) {
      ElMessage.error('已经是最后一题了');
      return;
    }

    if (direction === 'prev' && targetIndex < 0) {
      ElMessage.error('已经是第一题了');
      return;
    }

    const targetId = toolbarInfo.value.questionIds[targetIndex];
    router.push(`/question/detail/${targetId}?mode=study-plan&envId=${envId}`);
  } else {
    // 普通模式
    const targetId = direction === 'next'
        ? Number(currentId) + 1
        : Number(currentId) - 1;

    if (direction === 'prev' && targetId <= 0) {
      ElMessage.error('已经是第一题了');
      return;
    }

    router.push(`/question/detail/${targetId}`);
  }
}

const handleNext = () => handleNavigation('next');
const handlePrev = () => handleNavigation('prev');

const handleRandom = () => {
  const mode = route.query.mode;
  const envId = route.query.envId;
  const currentId = route.params.id;

  if (mode && envId) {
    // 学习计划模式
    if (toolbarInfo.value.questionIds.length === 0) {
      ElMessage.error('当前题目集中没有题目');
      return;
    }
    if (toolbarInfo.value.questionIds.length === 1) {
      ElMessage.error('题目集中只有一道题目');
      return;
    }

    let randomId;
    do {
      const randomIndex = Math.floor(Math.random() * toolbarInfo.value.questionIds.length);
      randomId = toolbarInfo.value.questionIds[randomIndex];
    } while (randomId === currentId);

    router.push(`/question/detail/${randomId}?mode=study-plan&envId=${envId}`);
  } else {
    // 普通模式 - 在1到3787中随机
    let randomId;
    do {
      randomId = Math.floor(Math.random() * 3787) + 1;
    } while (randomId.toString() === currentId);

    router.push(`/question/detail/${randomId}`);
  }
}

const fetchLastResult = async () => {
  eventBus.emit('showLast')
}

const toProfile = () => {
  router.push("/profile/" + userStore.loginUser.account)
}
</script>

<template>
  <div class="question-toolbar">
    <div class="left-section">
      <div class="logo" @click="toHome">
        <img src="../../public/favicon.ico" height="22" alt="favicon">
      </div>
      <div class="divider"></div>
      <el-button class="menu-button" :icon="Expand" @click="handleOpenTab">
        {{ toolbarInfo.title }}
      </el-button>
      <div class="nav-buttons">
        <el-tooltip
            content="上一题"
            placement="bottom"
            effect="light"
            :show-arrow="false"
        >
          <el-button text class="nav-button" @click="handlePrev"><</el-button>
        </el-tooltip>

        <el-tooltip
            content="下一题"
            placement="bottom"
            effect="light"
            :show-arrow="false"
        >
          <el-button text class="nav-button" @click="handleNext">></el-button>
        </el-tooltip>

        <el-tooltip
            content="随机一题"
            placement="bottom"
            effect="light"
            :show-arrow="false"
        >
          <el-button text class="nav-button" :icon="Switch" @click="handleRandom"/>
        </el-tooltip>
      </div>
    </div>

    <div class="center-section">
      <el-button type="primary" @click="fetchLastResult" :disabled="lastDisabled">
        <el-icon>
          <video-play/>
        </el-icon>
        查看上次提交
      </el-button>
      <el-button type="success" @click="handleSubmit" :disabled="!userStore.isLogin">
        <el-icon>
          <upload/>
        </el-icon>
        提交
      </el-button>
    </div>

    <div class="right-section">
      <div v-if="userStore.isLogin">
        <el-dropdown placement="bottom">
          <el-avatar shape="circle" :size="30" :src="avatar"/>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="toProfile">
                <el-icon>
                  <Setting/>
                </el-icon>
                个人中心
              </el-dropdown-item>
              <el-dropdown-item style="color: red" @click="logout">
                <el-icon>
                  <SwitchButton/>
                </el-icon>
                登出
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div v-else>
        <a class="register" @click="toLogin">注册</a>
        <a class="or">或</a>
        <a class="login" @click="toLogin">登录</a>
      </div>

    </div>
  </div>
</template>

<style scoped>
.question-toolbar {
  height: 100%;
  display: grid;
  grid-template-columns: 1fr auto 1fr;
  align-items: center;
  padding: 0 16px;
  background-color: #F0F0F0;
  border-bottom: 1px solid #ebeef5;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 8px;
}

.center-section {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 0 16px;
}

.right-section {
  color: #0000008c;
  display: flex;
  justify-content: flex-end;
}

.logo {
  margin-right: 0;
  display: flex;
  align-items: center;
}

.menu-button {
  height: 32px;
  border-radius: 3px;
  font-size: 14px;
  border: 1px solid #dcdfe6;
  background-color: #f4f4f5;
}

.menu-button:hover {
  background-color: #e9e9eb;
}

.nav-buttons {
  display: flex;
  gap: 0;
}

.nav-button {
  padding: 0 6px;
}

:deep(.el-button) {
  height: 32px;
  padding: 0 12px;
  border-radius: 3px;
}

:deep(.el-button--default) {
  border-color: #dcdfe6;
}

:deep(.el-button--default:hover) {
  background-color: #f4f4f5;
  border-color: #dcdfe6;
}

:deep(.el-button+.el-button) {
  margin-left: 0;
}

:deep(.el-button .el-icon) {
  margin-right: 4px;
}

.divider {
  width: 2px;
  height: 18px;
  background-color: #dcdfe6;
  margin: 0 5px;
}

.or {
  margin-left: 10px;
  margin-right: 10px;
}

.register:hover {
  color: #1a1a1a;
  cursor: pointer;
}

.login:hover {
  color: #1a1a1a;
  cursor: pointer;
}

.logo:hover {
  cursor: pointer;
}
</style>
